import { ResultEnum } from '@/enums/httpEnum'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import { AxiosError } from 'axios'
import { BaseRequestHttp, config } from './helper/axios'
import { checkStatus } from './helper/checkStatus'
import { ElMessage } from "element-plus";
import { tryHideFullScreenLoading } from "@/config/serviceLoading";
import router from "@/routers";

/**
 * pinia 错误使用说明示例
 * https://github.com/vuejs/pinia/discussions/971
 * https://github.com/vuejs/pinia/discussions/664#discussioncomment-1329898
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#single-page-applications
 */

class RequestHttp extends BaseRequestHttp {
	public constructor(config: AxiosRequestConfig) {

		const response = (response: AxiosResponse) => {
			if (response.data.code && response.data.code !== ResultEnum.SUCCESS) {
				ElMessage.error(response.data.msg);
				return Promise.reject(response.data);
			}
		}

		const error = (error: AxiosError) => {
			const { response } = error;
			tryHideFullScreenLoading();
			// 请求超时单独判断，因为请求超时没有 response
			if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试");
			// 根据响应的错误状态码，做不同的处理
			if (response) checkStatus(response.status);
			// 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
			if (!window.navigator.onLine) router.replace("/500");
			return Promise.reject(error);
		}

		
		// 实例化axios
		super(config, response, error);
	}
}

export default new RequestHttp(config);
